const { request,request2 } = require('./request')
const cheerio = require('cheerio');

// 获取tbs
async function getTBS() {
  const response = await request('http://tieba.baidu.com/dc/common/tbs')
  const data = await response.json()
  if(data && data.is_login && data.tbs){
    return data.tbs
  }else{
    return false
  }  
}

// 获取tbs
async function getTBS2(cookie) {
  const response = await request2('http://tieba.baidu.com/dc/common/tbs',cookie)
  const data = await response.json()
  if(data && data.is_login && data.tbs){
    return data.tbs
  }else{
    return false
  }  
}

// 获取tbs 16位
async function getTBS16(data) {
  const $ = cheerio.load(data)
  let scripts = $('script')
  let tbs='未找到符合要求的tbs值'
  for (let index = 0; index < scripts.length; index++) {
    const element = scripts[index];
    // 使用正确的方式获取script标签内的文本内容
    const scriptText = element.children[0] && element.children[0].data;
    if(scriptText){
      let k=scriptText.includes('var PageData = ')
      if(k){
        // 使用正则表达式匹配符合特点的tbs值
        var tbsMatch = scriptText.match(/tbs : \'([A-Za-z0-9]{16})\'/);
        if (tbsMatch && tbsMatch[1]) {
          tbs = tbsMatch[1];
        }
      }
    }
  }
  console.log('进入TBS获取方法',tbs)
  return tbs
}

module.exports = {
  getTBS,
  getTBS2,
  getTBS16
}